<template>
  <div id="content">
    <van-card
        v-for="team in props.teamList"
        :thumb="mouse"
        :desc="team.description"
        :title="`${team.name}`"
        :tag="teamStatusEnum[team.status]"
    >
      <!--      <template #tags>-->
      <!--        <van-tag plain type="danger" style="margin-right: 8px; margin-top: 8px">-->
      <!--          {{-->
      <!--            teamStatusEnum[team.status]-->
      <!--          }}-->
      <!--        </van-tag>-->
      <!--      </template>-->
      <template #bottom>
        <div>
          {{ `人数:${team.hasJoinList.length}/${team.maxnum}`}}
        </div>
        <div v-if="team.expiretime">
          {{ '过期时间: ' + team.expiretime }}
        </div>
        <div>
          {{ '创建时间: ' + team.createtime }}
        </div>
      </template>
      <template #footer>
        <van-button v-if="!team.hasJoinList.includes(currentUser?.id)" size="small" type="primary" plain
                    @click="()=>{
                      JoinTeamId=team.id;
                      console.log(JoinTeamId)
                      if (team.status==0){
                        doJoinTeam();
                      }else {
                        showPasswordDialog = true;
                      }
                    }">加入队伍
        </van-button>
        <van-button v-if="team.userid === currentUser?.id" size="small" plain
                    @click="doUpdateTeam(team.id)">更新队伍
        </van-button>
        <van-button v-if="team.hasJoinList.includes(currentUser?.id) && team.userid !== currentUser?.id"
                    size="small" type="primary" plain
                    @click="doQuitTeam(team.id)">退出队伍
        </van-button>
        <van-button v-if="team.userid === currentUser?.id" size="small" type="primary" plain
                    @click="doDeleteTeam(team.id)">解散队伍
        </van-button>
      </template>
    </van-card>
  </div>
  <van-dialog v-model:show="showPasswordDialog" title="请输入密码" show-cancel-button @confirm="doJoinTeam"
              @cancel="doCancelDialog">
    <van-field v-model="password" placeholder="请输入密码"/>
  </van-dialog>
</template>

<script setup lang="ts">
import type {TeamType} from "../models/team.d.ts";
import mouse from '../assets/mouse.jpg';
import myAxios from "../plugins/myAxios";
import {showSuccessToast} from "vant";
import {teamStatusEnum} from "../constants/team.ts";
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {getCurrentUser} from "../services/user.ts";

const showPasswordDialog = ref(false);
const password = ref('');
const JoinTeamId = ref<number | null>(null); // 设置初始值为 null
const routes = useRouter()

interface TeamCardListProps {
  teamList: TeamType[];
}

const props = withDefaults(defineProps<TeamCardListProps>(), {
  // @ts-ignore
  teamList: [] as TeamType[],
});
const emit = defineEmits(['update:teamList']);

/**
 * 加入队伍
 */
const doJoinTeam = async () => {
  if (!JoinTeamId.value) {
    console.error('当前队伍 ID 无效');
    return;
  }
  const res = await myAxios.post('/team/join', {
    teamId: JoinTeamId.value,
    password: password.value
  });
  //@ts-ignore
  if (res?.code === 0) {
    showSuccessToast('加入成功')
    reload()
  } else {
    //@ts-ignore
    showSuccessToast(`加入失败${res.description ? `，${res.description}` : ''}`)
  }
}

/**
 * 取消
 */
const doCancelDialog = () => {
  password.value = '';
  showPasswordDialog.value = false;
}

const currentUser = ref();

onMounted(async () => {
  currentUser.value = await getCurrentUser();
  console.log(currentUser.value)
})

/**
 * 跳转至更新队伍页
 * @param id
 */
const doUpdateTeam = (id: number) => {
  routes.push({
    path: '/team/update',
    query: {
      id,
    }
  })
}

/**
 * 退出队伍
 * @param id
 */
const doQuitTeam = async (id: number) => {
  const res = await myAxios.post('/team/quit', {
    teamId: id
  });
  if (res?.code === 0) {
    showSuccessToast('操作成功');
    reload()
  } else {
    showSuccessToast('操作失败' + (res.description ? `，${res.description}` : ''));
  }
}

/**
 * 解散队伍
 * @param id
 */
const doDeleteTeam = async (id: number) => {
  const res = await myAxios.post('/team/delete', {
    teamId: id
  });
  if (res?.code === 0) {
    showSuccessToast('操作成功');
    reload()
  } else {
    showSuccessToast('操作失败' + (res.description ? `，${res.description}` : ''));
  }

}

/**
 * 加载团队列表
 */
const reload = async () => {
  try {
    const res = await myAxios.get('/team/list');
    emit('update:teamList', res.data); // 通知父组件更新数据
  } catch (error) {
    console.error('加载团队列表失败', error);
  }
};


</script>

<style scoped>
#teamCardList :deep(.van-image__img) {
  height: 128px;
  object-fit: unset;
}


#content {
  padding-bottom: 50px;
}
</style>